//
//  AVPlayControllerViewController.m
//  MY Project For Sport
//
//  Created by dllo on 16/3/2.
//  Copyright © 2016年 dilo. All rights reserved.
//

#import "AVPlayControllerViewController.h"
#import "NetworkingHandlerOfBlock.h"
#import "ModelForAV.h"
#import "CellForAVNews.h"
#import <AVFoundation/AVFoundation.h>

#define WEIGHTT [UIScreen mainScreen].bounds.size.width / 375
#define HEIGHTT [UIScreen mainScreen].bounds.size.height / 667

#define WIDTH  self.playerView.frame.size.width
#define HEIGHT self.playerView.frame.size.height

@interface AVPlayControllerViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain)UITableView *tableView;
@property (nonatomic, retain)NSMutableArray *array;


// 整个的播放界面
@property (nonatomic, retain)  UIView *playerView;

@property(nonatomic,assign)BOOL isPlay;
@property(nonatomic,retain)AVPlayerLayer *playerLayer;
@property(nonatomic,retain)AVPlayer *player;
@property(nonatomic,retain)AVPlayerItem *playerItem;
@property (nonatomic, assign) CGFloat totalMovieDuration; // 保存该视频资源的总时长，快进或快退的时候要用

@property(nonatomic,assign)BOOL isTap;


// 底部(滑动条 播放按键 时间)的 view
@property (retain, nonatomic) UIView *bottomView;

// 时间
@property (retain, nonatomic) UILabel *timeLabel;
// 滑动条
@property (retain, nonatomic) UISlider *ProgressSlider;
// 播放按键
@property (retain, nonatomic) UIButton *playerButton;

@property (nonatomic, assign)BOOL first;



@end

@implementation AVPlayControllerViewController

- (void)dealloc {

    
    [_tableView release];
    [_array release];
    [_playerView release];
    [_player release];
    [_playerLayer release];
    [_playerItem release];
    [_bottomView release];
    [_timeLabel release];
    [_ProgressSlider release];
    [_playerButton release];
    [_flashUrl release];
    
    [super dealloc];
    
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationController.navigationBarHidden = YES;
    
    [self handleData];
    [self createTableView];
    
    [self createSubview];
    

    [self createBackButton];
    [self addNotificationRote];
    
//    [[NSNotificationCenter defaultCenter] addObserverForName:@"ddd" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
////    
////        AVView *avView = [[AVView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height / 2.5 + 16 * HEIGHTT)];
////        [self.view addSubview:avView];
////        [avView release];
////        
////        NSString *url = @"http://v.iask.com/v_play_ipad.php?vid=";
////    
////        NSString *url2 = [url stringByAppendingFormat:@"%@", [note.userInfo objectForKey:@"player"]];
////    
////       // NSLog(@"%@", [note.userInfo objectForKey:@"player"]);
////    
////        [avView passModelUrl:url2];
//        
//        
//    }];
//
    
    
    
}

- (void)createSubview {
    
    self.flashUrl = [self.flashUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    self.playerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height / 2.5)];
    [self.view addSubview:self.playerView];
    [_playerView release];
    self.playerView.backgroundColor = [UIColor yellowColor];
    
    self.playerItem = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:self.flashUrl]];
    self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
    [_playerItem release];
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    
    self.playerLayer.frame = CGRectMake(5 * WEIGHTT, 5 * HEIGHTT, self.view.frame.size.width - 10 * WEIGHTT,  self.view.frame.size.height / 2.5 - 10 * HEIGHTT);
    self.playerLayer.videoGravity = AVLayerVideoGravityResize;
    
    [self.playerView.layer insertSublayer:self.playerLayer above:0];
    
    
    self.bottomView = [[UIView alloc] init];
    [self.playerView addSubview:self.bottomView];
    [_bottomView release];
    self.bottomView.frame = CGRectMake(0,HEIGHT / 6 * 5, WIDTH, HEIGHT / 6);
    self.bottomView.backgroundColor = [UIColor colorWithRed:0 green:0.1 blue:0.1 alpha:0.8];
    
    self.timeLabel = [[UILabel alloc] init];
    [self.bottomView addSubview:self.timeLabel];
    [_timeLabel release];
    self.timeLabel.frame = CGRectMake(WIDTH - 95 * WEIGHTT, 5 * HEIGHTT, 90 * WEIGHTT, HEIGHT / 6 - 10 * HEIGHTT);
    self.timeLabel.textColor = [UIColor whiteColor];
   // self.timeLabel.backgroundColor = [UIColor orangeColor];
    
    
    self.ProgressSlider = [[UISlider alloc] init];
    [self.bottomView addSubview:self.ProgressSlider];
    [_ProgressSlider release];
    self.ProgressSlider.frame = CGRectMake(40 * WEIGHTT, 5 * HEIGHTT, WIDTH - 140 * WEIGHTT , HEIGHT / 6 - 10 * HEIGHTT);
    
    self.playerButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.bottomView addSubview:self.playerButton];
    [self.playerButton addTarget:self action:@selector(pause:) forControlEvents:UIControlEventTouchUpInside];
    self.playerButton.frame = CGRectMake(5 * WEIGHTT, 5 * HEIGHTT, 30 * WEIGHTT, HEIGHT / 6 - 10 * HEIGHTT);
    [self.playerButton setImage:[UIImage imageNamed:@"iconfont-bofang"] forState:UIControlStateNormal];

    
    [self.player play];
    
    [self addTapGesture];
    
    [self addProgressObserver];
    
    
    

}

// 获取视频总时长
- (void)addProgressObserver {
    
    //设置(1,1) 设置每秒执行一次
    
    [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue: dispatch_get_main_queue() usingBlock:^(CMTime time) {
        
        
        //总时长 将CMTime类型转成float类型
        CGFloat duration = CMTimeGetSeconds(self.playerItem.duration);
        
        //当前时间
        CGFloat current = CMTimeGetSeconds(self.player.currentTime);
        
        //倒计时
        CGFloat rem = duration - current;
        
        NSString *totalT = [NSString stringWithFormat:@"%02d:%02d",(int)rem/60 ,(int)rem%60];
        NSString *currenT = [NSString stringWithFormat:@"%02d:%02d",(int)current/60 ,(int)current%60];
        
        NSString *timeStr = [NSString stringWithFormat:@"%@/%@",currenT,totalT];
        self.timeLabel.text = timeStr;
        self.timeLabel.font = [UIFont systemFontOfSize:15];
        self.timeLabel.adjustsFontSizeToFitWidth = YES;
        //保存总时长用于手动快进和快退
        self.totalMovieDuration = duration;
         
        //设置进度值 当前时间/总时长
        self.ProgressSlider.value = current/duration;
        
        [self.ProgressSlider addTarget:self action:@selector(toAnyTime:) forControlEvents:UIControlEventValueChanged];
        
    }];
    
}

// 滑动条调到任意时间播放
- (void)toAnyTime:(UISlider *)time {
    
    UISlider *slider = time;
    
    //获取当前时间
    double currentTime = self.totalMovieDuration * slider.value;
    CMTime dragedCMTime = CMTimeMake(currentTime, 1);
    [self.player seekToTime:dragedCMTime completionHandler:^(BOOL finished) {
        
        [self.player play];
        
    }];
    
    
}


// 轻拍屏幕下方的 播放 滑动条 时间显示消失
- (void)addTapGesture {
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(boomDismiss)];
    
    [self.playerView addGestureRecognizer:tap];
    
    [tap release];
}

- (void)boomDismiss {
    
    if (self.isTap == NO) {
        
        [UIView animateWithDuration:0.5 animations:^{
            
            self.bottomView.alpha = 0;
        }];
        
    }else {
        
        [UIView animateWithDuration:0.5 animations:^{
            
            self.bottomView.alpha = 0.7;
            
        }];
        
    }
    
    self.isTap = !self.isTap;
}

// 暂停或播放

- (void)pause:(UIButton *)button {
    
    if (self.isPlay) {
        [self.playerButton setImage:[UIImage imageNamed:@"iconfont-bofang"] forState:UIControlStateNormal];
        [self.player play];
    }else
    {
        [self.playerButton setImage:[UIImage imageNamed:@"iconfont-zanting"] forState:UIControlStateNormal];
        [self.player pause];
    }
    self.isPlay = !self.isPlay;
    
}

/** 添加播放完毕的观察者 */
- (void)addNotificationEnd {
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    
}

- (void)playEnd:(NSNotification *) end {
    
    NSLog(@"播放完毕");
    
}

/** 添加屏幕旋转的观察者 */
- (void)addNotificationRote {
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(beginRote:) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
    
    
}

- (void)beginRote:(NSNotification *)notification {
    
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    
    // 向右横屏
    if (orientation == UIInterfaceOrientationLandscapeRight) {
        
        
        [self setPlayerLayerFrame];
    }
    // 向左横屏
    if (orientation == UIInterfaceOrientationLandscapeLeft) {
        
        [self setPlayerLayerFrame];
        
    }
    // 竖屏播放
    if (orientation == UIInterfaceOrientationPortrait) {
        
        [self setVerticalFrame];
    }
    
}

//  横屏的时候frame
- (void)setPlayerLayerFrame {
    
    self.playerLayer.frame = CGRectMake(5, 5, self.view.frame.size.width, self.view.frame.size.height);
    self.playerView.frame = CGRectMake(5, 5, self.view.frame.size.width, self.view.frame.size.height);
    
}

 // 竖屏的时候frame
- (void)setVerticalFrame {
    
    
self.playerView.frame = CGRectMake(5, 5, self.view.frame.size.width - 10, self.view.frame.size.height / 2.5 - 10);
    
 self.playerLayer.frame = CGRectMake(5, 5, self.view.frame.size.width - 10, self.view.frame.size.height / 2.5 - 10);
    
}


- (void)createBackButton {

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(10 * WEIGHTT, 10 * HEIGHTT, 30 * WEIGHTT, 30 * HEIGHTT);
    
    [self.view addSubview:button];
    
    [button setImage:[UIImage imageNamed:@"iconfont-zuojiantou"] forState:UIControlStateNormal];
    
    [button addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];

}

- (void)backAction:(UIButton *) button {

    self.navigationController.navigationBarHidden = NO;
    [self.player pause];
    
    [self.navigationController popToRootViewControllerAnimated:YES];
    
}

- (void)handleData {
    
    NSString *url =@"http://platform.sina.com.cn/sports_client/ad_list?app_key=2586208540&_version__=3.2.1.01&__os__=android&partner=clear&pos=sports&client_deviceid=7005145ee5bbe7f1f97c5e227f4ab771";
    
    [NetworkingHandler networkingWithUrl:url completeHandle:^(NSURLResponse *response, NSData *data, id result) {
        
        self.array = [NSMutableArray array];
        NSDictionary *dic = [result objectForKey:@"result"];
        NSArray *array = [dic objectForKey:@"data"];
        for (NSDictionary *dict in array) {
            
            ModelForAV *model = [[ModelForAV alloc] init];
            
            [model setValuesForKeysWithDictionary:dict];
            [self.array addObject:model];
        
            [model release];
            
        }
        
        
        [self.tableView reloadData];
        
    }];
    
}

- (void)createTableView {

    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height / 2.5, self.view.frame.size.width, self.view.frame.size.height - self.view.frame.size.height / 2.5) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    [_tableView release];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
     [self.tableView registerClass:[CellForAVNews class] forCellReuseIdentifier:@"poolForCell"];


}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.array.count;


}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    CellForAVNews *cell = [tableView dequeueReusableCellWithIdentifier:@"poolForCell"];
    
    ModelForAV *model = [self.array objectAtIndex:indexPath.row];
    
    [cell passModelForAv:model];
    
    return cell;

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return self.view.frame.size.height / 8;


}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    ModelForAV *model = [self.array objectAtIndex:indexPath.row];
    
    NSString *str = @"http://v.iask.com/v_play_ipad.php?vid=";
    NSString *url = [str stringByAppendingFormat:@"%@", model.ipad_vid];
    
    self.playerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:url]];
    
    [self.player replaceCurrentItemWithPlayerItem:self.playerItem];
    
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"ddd" object:nil userInfo:@{@"player": model.ipad_vid}];
//

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
